<template>
  <div class="crud-opts">
    <span class="crud-opts-left">
      <!--左侧插槽-->
      <slot name="left" />
      <el-button
        v-if="crud.optShow.add"
        v-permission="permission.add"
        class="filter-item"
        size="mini"
        type="primary"
        @click="crud.toAdd"
      >
        新增
      </el-button>
      <el-button
        v-if="crud.optShow.edit"
        v-permission="permission.edit"
        :disabled="crud.selections.length !== 1"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.toEdit(crud.selections[0])"
      >
        修改
      </el-button>
      <el-button
        v-if="crud.optShow.del"
        slot="reference"
        v-permission="permission.del"
        :disabled="crud.selections.length === 0"
        :loading="crud.delAllLoading"
        class="filter-item"
        size="mini"
        type="danger"
        @click="toDelete(crud.selections)"
      >
        删除
      </el-button>
      <el-button
        v-if="crud.optShow.leadingIn"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="doLeadingIn"
      >导入</el-button>
      <el-button
        v-if="crud.optShow.download"

        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="crud.doExport"
      >导出</el-button>
      <el-button
        v-if="crud.optShow.downloadDetail"

        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="crud.toExportDetail"
      >导出详情</el-button>
      <el-button
        v-if="crud.optShow.enable"
        :disabled="crud.selections.length === 0"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.enableOrDisable('ENABLE')"
      >启用</el-button>
      <el-button
        v-if="crud.optShow.disable"
        :disabled="crud.selections.length === 0"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="danger"
        @click="crud.enableOrDisable('DISABLE')"
      >禁用</el-button>
      <el-button
        v-if="crud.optShow.pass&&!isDetail"
        v-permission="crud.optShow.pass"
        class="filter-item"
        size="mini"
        type="success"
        :disabled="crud.selections.length < 1"
        @click="crud.enableOrDisable('PASS')"
      >
        审核
      </el-button>
      <el-button
        v-if="crud.optShow.reject&&!isDetail"
        v-permission="crud.optShow.reject"
        class="filter-item"
        size="mini"
        type="danger"
        :disabled="crud.selections.length < 1"
        @click="crud.enableOrDisable('REJECT')"
      >
        反审
      </el-button>
      <el-button
        v-if="crud.optShow.pass&&isDetail"
        v-permission="crud.optShow.pass"
        class="filter-item"
        size="mini"
        type="success"
        :disabled="$route.params.id == 'add'"
        @click="crud.enableOrDisable('PASS',$route.params.id)"
      >
        审核
      </el-button>
      <el-button
        v-if="crud.optShow.reject&&isDetail"
        v-permission="crud.optShow.reject"
        class="filter-item"
        size="mini"
        type="danger"
        :disabled="$route.params.id == 'add'"
        @click="crud.enableOrDisable('REJECT',$route.params.id)"
      >
        反审
      </el-button>
      <el-button
        v-if="crud.optShow.invalid"
        :disabled="crud.selections.length !== 1"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.enableOrDisable('INVALID')"
      >作废</el-button>
      <el-button
        v-if="crud.optShow.recover"
        :disabled="crud.selections.length !== 1"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="danger"
        @click="crud.enableOrDisable('RECOVER')"
      >取消作废</el-button>
      <el-button
        v-if="crud.optShow.accept&&isDetail"
        :disabled="$route.params.id == 'add'"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.toAccept($route.params.id)"
      >验收</el-button>
      <el-button
        v-if="crud.optShow.unAccept&&isDetail"
        :disabled="$route.params.id == 'add'"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="danger"
        @click="crud.toUnAccept($route.params.id)"
      >反验收</el-button>
      <el-button
        v-if="crud.optShow.accept&&!isDetail"
        :disabled="$route.params.id == 'add'"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="success"
        @click="crud.toAccept()"
      >验收</el-button>
      <el-button
        v-if="crud.optShow.unAccept&&!isDetail"
        :disabled="$route.params.id == 'add'"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="danger"
        @click="crud.toUnAccept()"
      >反验收</el-button>
      <!--      <el-button-->
      <!--        slot="right"-->
      <!--        class="filter-item"-->
      <!--        size="mini"-->
      <!--        type="warning"-->
      <!--        @click="isColumn = true"-->
      <!--      >-->
      <!--        自定义列-->
      <!--      </el-button>-->
      <el-button
        v-if="crud.optShow.copy"
        :disabled="crud.selections.length !== 1"
        :loading="crud.copyLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="crud.toCopy()"
      >复制</el-button>
      <el-button
        v-if="crud.optShow.print&&isDetail"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        :disabled="$route.params.id == 'add'"
        @click="crud.preView"
      >打印</el-button>
      <el-button
        v-if="crud.optShow.printDetail&&isDetail"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        :disabled="$route.params.id == 'add'"
        @click="crud.preView1"
      >打印预览</el-button>
      <el-button
        v-if="crud.optShow.print&&!isDetail"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="crud.preView"
      >打印</el-button>
      <el-button
        v-if="crud.optShow.printDetail&&!isDetail"
        :loading="crud.downloadLoading"
        class="filter-item"
        size="mini"
        type="warning"
        @click="crud.preView1"
      >打印预览</el-button>
      <!--右侧-->
      <slot name="right" />
    </span>
    <el-button-group v-if="showRight" class="crud-opts-right">
      <el-button
        icon="el-icon-search"
        plain
        size="mini"
        type="info"
        @click="toggleSearch()"
      />
      <el-button
        icon="el-icon-refresh"
        size="mini"
        @click="crud.refresh()"
      />
      <el-popover
        placement="bottom-end"
        trigger="click"
        width="200"
      >
        <el-button
          slot="reference"
          icon="el-icon-s-grid"
          size="mini"
        >
          <i
            aria-hidden="true"
            class="fa fa-caret-down"
          />
        </el-button>
        <div style="max-height: 80vh;overflow: scroll">
          <el-checkbox
            v-model="allColumnsSelected"
            :indeterminate="allColumnsSelectedIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox
            v-for="item in crud.props.tableColumns"
            :key="item.label"
            v-model="item.visible"
            @change="handleCheckedTableColumnsChange(item)"
          >
            {{ item.label }}
          </el-checkbox>
        </div>
      </el-popover>
    </el-button-group>
    <el-dialog
      title="自定义列"
      :visible.sync="isColumn"
      width="400px"
    >
      <el-tree
        :data="crud.header"
        node-key="id"
        default-expand-all
        draggable
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        @node-drag-start="handleDragStart"
        @node-drag-enter="handleDragEnter"
        @node-drag-leave="handleDragLeave"
        @node-drag-over="handleDragOver"
        @node-drag-end="handleDragEnd"
        @node-drop="handleDrop"
      />
    </el-dialog>
    <!--导入-->
    <el-dialog
      :title="crud.title + '导入数据'"
      :visible.sync="importStatus"
      width="400px"
    >
      <el-upload
        ref="upload_import"
        :action="action"
        :auto-upload="false"
        :before-upload="beforeUpload"
        :headers="headers"
        :limit="1"
        :on-error="handleError"
        :on-success="handleSuccess"
        accept=".xlsx, .xls"
      >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <div class="tpl">
        <el-button
          size="small"
          type="info"
          @click="downloadTemplate"
        >下载模板
        </el-button>
        <span class="tips">提示：仅允许导入.xls或.xlsx格式文件</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="importStatus=false">取消</el-button>
        <el-button
          :loading="crud.cu === 2"
          type="primary"
          @click="handleSubmit"
        >确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, { crud } from '@crud/crud'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

export default {
  mixins: [crud()],
  props: {
    permission: {
      type: Object,
      default: null
    },
    showRight: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      url: '',
      isDetail: false,
      allColumnsSelected: true,
      uploadDialgShow: false,
      importStatus: false,
      isColumn: false,
      headers: { Authorization: getToken() },
      downLoadName: this.crud.title + '.xlsx',
      allColumnsSelectedIndeterminate: false
    }
  },
  computed: {
    action() {
      const baseURL =
        process.env.NODE_ENV === 'production'
          ? process.env.VUE_APP_BASE_API + '/'
          : '/'
      if (process.env.NODE_ENV === 'production') {
        return this.url + '/import'
      } else {
        return baseURL + this.crud.url + '/import'
      }
    }
  },
  created() {
    this.url = [...window.location.href.split('/').slice(0, 3), ...this.crud.url.split('/')].join('\/')
    console.log(this.url)
    if (this.$route.params.id) {
      this.isDetail = true
    } else {
      this.isDetail = false
    }
    // if(this.crud.name.indexOf("Detail") != -1){
    //   this.crud.optShow.reject = true
    // }
    this.crud.updateProp('searchToggle', true)
  },
  methods: {
    handleDragStart(node, ev) {
    },
    handleDragEnter(draggingNode, dropNode, ev) {
    },
    handleDragLeave(draggingNode, dropNode, ev) {
    },
    handleDragOver(draggingNode, dropNode, ev) {
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      this.crud.toUpdateHeader()
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      // this.crud.toUpdateHeader()
    },
    allowDrop(draggingNode, dropNode, type) {
      if (type !== 'inner') {
        return true
      }
    },
    allowDrag(draggingNode) {
      return draggingNode.data.label.indexOf('三级 3-2-2') === -1
    },
    doLeadingIn() {
      this.importStatus = true
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      console.log('handleSuccess', response)
      if (response !== '导入成功') {
        const a = document.createElement('a')
        a.setAttribute('href', response.data.result)
        a.click()
      } else {
        this.crud.notify(response, CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.$refs.upload.clearFiles()
        this.uploadDialgShow = false
        this.crud.refresh()
      }
    },
    handleError(err, file, fileList) {
      this.crud.notify(
        ' -_- !~~ 服务器开小差了，稍后重试',
        CRUD.NOTIFICATION_TYPE.WARNING
      )
    },
    handleSubmit() {
      // this.crud.doImport()
      this.$refs.upload_import.submit()
    },
    handleCancel() {
      this.$refs.upload.clearFiles()
      this.uploadDialgShow = false
    },
    downloadTemplate() {
      request({
        url: 'api/common/downloadExcelTemplate?name=' + this.downLoadName,
        method: 'get',
        responseType: 'blob'
      }).then((res) => {
        const a = document.createElement('a')
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel'
        })
        const objectUrl = URL.createObjectURL(blob)
        a.setAttribute('href', objectUrl)
        a.setAttribute('download', this.downLoadName)
        a.click()
      })
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function() {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
    }
  }
}
</script>

<style scoped lang="scss">
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}

.tpl {
  margin-top: 20px;
}

.filter-item {
  & + .filter-item {
    margin-left: 5px !important;
  }
}

.el-tree-node {
  border-top: 1px solid #DDDDDD !important;
  border-left: 1px solid #DDDDDD !important;
  border-right: 1px solid #DDDDDD !important;
  white-space: nowrap;
  outline: 0;
}
</style>
